package net.p2pcdn.task;

import net.p2pcdn.core.order.domain.CDNConsumeRecord;
import net.p2pcdn.core.order.repository.CDNConsumeRecordRepository;
import net.p2pcdn.core.order.service.CDNConsumeRecordService;
import net.p2pcdn.core.order.service.DataMergeBO;
import net.p2pcdn.core.order.service.Task;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Component
public class TaskRetryHandler {
    @Resource
    private CDNConsumeRecordRepository cdnConsumeRecordRepository;
    @Autowired
    private CDNConsumeRecordService cdnConsumeRecordService;
    @Autowired
    private ThreadPoolTaskExecutor springThreadPoolTaskExecutor;

    @Scheduled(cron = "0 17 * * * ?")
    public void doTask() {
        int limit = 1000;
        List<CDNConsumeRecord> recordList = null;
        do {
            Date from = DateUtils.addHours(new Date(), -1);
            recordList = cdnConsumeRecordRepository.findUndoRecord(limit, from);
            DataMergeBO bo = cdnConsumeRecordService.mergeTrafficAmount(recordList);
            bo.getDomainRelatedTraffic().forEach((k, v) -> {
                Task task = new Task(k, new BigDecimal(v), bo.getDomainRelatedRecordIds().get(k));
                springThreadPoolTaskExecutor.execute(new CDNConsumeRecordService.Worker(task, cdnConsumeRecordService));
            });
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (recordList.size() > 0);
    }
}
